from db.schema import UserModelSchema, UserLoginSchema
from fastapi import APIRouter, Depends, HTTPException
from werkzeug.security import check_password_hash
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import JSONResponse
from db.crud import UserModelCrud, QueryCrud
from utils.jwt_token import JWTToken
from db.models import UserModel
from db.database import get_db

# 创建API路由实例
router = APIRouter(
    prefix="/user",
    tags=["用户增删改查"],
    responses={404: {"description": "Not found"}},
)


@router.post("/register", tags=["用户注册"])
async def register_user(user_info: UserModelSchema, db: AsyncSession = Depends(get_db)):
    # 调用 UserModelCrud 中的 create_user 方法，创建用户
    add_user, msg = await UserModelCrud.create_user(db=db, user=dict(user_info), model=UserModel, return_msg="注册成功")
    return JSONResponse(status_code=201, content=msg)


@router.post("/login", tags=["用户登录"])
async def read_userinfo(user_login_info: UserLoginSchema, db: AsyncSession = Depends(get_db)):
    # 调用 QueryCrud 中的 get_one_info 方法，查询数据库是否存在该用户
    select_user, user_info = await QueryCrud.get_one_info(db=db, select_model=UserModel,
                                                          select_model_info=UserModel.account,
                                                          select_info=user_login_info.account)
    print("是否存在:", select_user, "用户信息:", user_info)
    if not select_user:
        raise HTTPException(status_code=400, detail={"code": 400, "success": False, "msg": "用户不存在"})

    if not check_password_hash(user_info.password, user_login_info.password):
        raise HTTPException(status_code=500, detail={"code": 400, "success": False, "msg": "密码错误", })

    # 用户信息
    userinfo = {
        'uuid': user_info.uuid,
        'account': user_info.account,
        'name': user_info.name,
        'age': user_info.age
    }
    return JSONResponse(status_code=200, content={"code": 200, "success": True, "msg": "登录成功",
                                                  "userinfo": userinfo,
                                                  "token": JWTToken.generate_token(userinfo)})


@router.put("/update", tags=["更新用户信息"])
async def update_student_info(user_info: UserModelSchema, db: AsyncSession = Depends(get_db),
                              current_user: dict = Depends(JWTToken())):
    # 调用 UserModelCrud 中的 update_user 方法，更新用户信息
    update_info, msg = await UserModelCrud.update_user(db, current_user, dict(user_info), UserModel, "信息更新成功")
    return JSONResponse(status_code=201, content=msg)


@router.delete("/delete", tags=["删除用户(注销)"])
async def delete_student(db: AsyncSession = Depends(get_db), current_user: dict = Depends(JWTToken())):
    delete_user, msg = await UserModelCrud.delete_user(db, current_user, UserModel, "用户注销成功")
    return JSONResponse(status_code=200, content=msg)


@router.get("/select_all", tags=["查询所有用户信息"])
async def update_student_info(db: AsyncSession = Depends(get_db), current_user: dict = Depends(JWTToken())):
    # 调用 QueryCrud 中的 get_all_info 方法，查询所有信息
    select_all = await QueryCrud.get_all_info(db=db, select_model=UserModel)
    info_list = []
    for i in select_all:
        info_dict = {
            'id': i.id,
            'uuid': i.uuid,
            'account': i.account,
            'name': i.name,
            'age': i.age,
            'join_time': i.join_time.strftime("%Y-%m-%d"),
        }
        info_list.append(info_dict)
    return JSONResponse(status_code=200, content={"code": 201, "success": True, "data": info_list})


@router.get("/token", tags=["验证token/解密token信息"])
async def token(current_user: dict = Depends(JWTToken())):
    # 返回验证成功的信息和用户信息
    return JSONResponse(status_code=200, content={"code": 200, "success": True, "msg": "验证成功",
                                                  "user_info": current_user})
